package com.xyt.imei.core.api;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.NoSuchElementException;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Workbook;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.luminary.common.framework.core.auth.ValidateToken;
import com.luminary.common.framework.core.model.SimpleResponse;
import com.luminary.component.util.common.ExcelUtil;
import com.xyt.imei.core.meta.RoleEnum;
import com.xyt.imei.core.model.dto.ExtraStoreExcelDTO;
import com.xyt.imei.core.model.po.User;
import com.xyt.imei.core.model.vo.ErrorInfoVO;
import com.xyt.imei.core.service.ExtraStoreService;
import com.xyt.imei.core.service.impl.ExtraStoreServiceImpl.ValidateInfo;
import com.xyt.imei.core.util.TokenUtil;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping("store/extra")
public class ExtraStoreApi {

	@Autowired
	private TokenUtil tokenUtil;
	
	@Autowired
	private ExtraStoreService extraStoreService;
	
	@SuppressWarnings("unchecked")
	@ValidateToken(roles = {RoleEnum.ADMIN_VALUE + "",  RoleEnum.CMCC_VALUE + ""})
	@PostMapping("/file")
	public SimpleResponse create(
			@RequestParam("dataFile") MultipartFile dataFile,
			HttpServletResponse response) throws Exception {
		log.info("file:{size:" + dataFile.getSize() + ",name:" + dataFile.getOriginalFilename() + ",contentType:" + dataFile.getContentType());
		
		User user = tokenUtil.getUser();
		if(user == null)
			return SimpleResponse.badRequest("用户信息为空", response);
		
		if(user.getExtraFlag() == null || user.getExtraFlag().intValue() != 1) {
			return SimpleResponse.badRequest("用户没有权限", response);
		}
		
		if(!dataFile.getOriginalFilename().endsWith("xls") && !dataFile.getOriginalFilename().endsWith("xlsx"))
			return SimpleResponse.badRequest("文件格式不正确", response);
		
		ImportParams params = new ImportParams();
		List<ExtraStoreExcelDTO> storeExtraExcelList = new ArrayList<ExtraStoreExcelDTO>();
		try {
			storeExtraExcelList = (List<ExtraStoreExcelDTO>) ExcelUtil.importExcel(dataFile.getInputStream(), ExtraStoreExcelDTO.class, params);
			if(storeExtraExcelList.size() == 0)
				return SimpleResponse.failed("导入的是张空表", response);
		} catch(NoSuchElementException e) {
			return SimpleResponse.failed("导入的模板不正确", response);
		}
		
		ValidateInfo validateInfo = extraStoreService.addExtraStore(storeExtraExcelList, user);
		if(validateInfo.getErrorInfo() != null && !validateInfo.getErrorInfo().isEmpty()) {
			StringBuffer stringBuffer = new StringBuffer();
			List<ErrorInfoVO> errorInfoList = validateInfo.getErrorInfo();
			for(ErrorInfoVO errorInfo : errorInfoList) {
				stringBuffer.append(errorInfo.toString());
			}
			return SimpleResponse.success("导入操作完成，存在失败信息:" + stringBuffer.toString(), response);
		}
		
		return SimpleResponse.success("导入操作完成", response);
	}
	
	@GetMapping("/all")
	@ResponseBody
	public void listAll(
			@RequestParam("token") String token,
			HttpServletResponse response) throws Exception {
		
		log.info("list all");
		
		User user = tokenUtil.getUser(token);
		if(user == null)
			return;
		
		if(user.getExtraFlag() == null ||  user.getExtraFlag().intValue() != 1)
			return;
		
		Workbook workbook = extraStoreService.export();
		response.reset();
		response.setHeader("Set-Cookie", "fileDownload=true; path=/");
		if(workbook == null)
			return;
		
		response.setContentType("application/vnd.ms-excel");
		String fileName = "串号" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
		response.setHeader("Content-disposition","attachment; filename="+new String(fileName.getBytes("gb2312"),"ISO-8859-1")+".xls");
		ServletOutputStream outStream=null;
		try{
		   outStream = response.getOutputStream();
		   workbook.write(outStream);
		}finally{
		   outStream.close();
		}
		
	}
	
	@GetMapping("/diff")
	@ResponseBody
	public void listDiff(
			@RequestParam("token") String token,
			HttpServletResponse response) throws Exception {
		
		log.info("list all");
		
		User user = tokenUtil.getUser(token);
		if(user == null)
			return;
		
		if(user.getExtraFlag() == null || user.getExtraFlag().intValue() != 1)
			return;
		
		Workbook workbook = extraStoreService.exportDiff();
		response.reset();
		response.setHeader("Set-Cookie", "fileDownload=true; path=/");
		if(workbook == null)
			return;
		
		response.setContentType("application/vnd.ms-excel");
		String fileName = "串号" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
		response.setHeader("Content-disposition","attachment; filename="+new String(fileName.getBytes("gb2312"),"ISO-8859-1")+".xls");
		ServletOutputStream outStream=null;
		try{
		   outStream = response.getOutputStream();
		   workbook.write(outStream);
		}finally{
		   outStream.close();
		}
		
	}
	
}
